package dao

import (
	"database/sql"
	models "dict-server/dao/model"
	"fmt"
)

// WordDAO 单词数据访问对象
type WordDAO struct {
	db *sql.DB
}

// NewWordDAO 创建单词DAO实例
func NewWordDAO(db *sql.DB) *WordDAO {
	return &WordDAO{db: db}
}

// GetWord 查询单词详情
func (d *WordDAO) GetWord(word string) (*models.Word, error) {
	query := "SELECT word, trans FROM words WHERE word = ?"

	var w models.Word
	err := d.db.QueryRow(query, word).Scan(&w.Word, &w.Trans)
	switch {
	case err == sql.ErrNoRows:
		return nil, nil // 单词不存在
	case err != nil:
		return nil, fmt.Errorf("查询失败: %w", err)
	default:
		return &w, nil
	}
}

// InsertWords 批量插入单词
func (d *WordDAO) InsertWords(words []models.Word, batchSize int) (int, error) {
	if len(words) == 0 {
		return 0, nil
	}

	totalInserted := 0
	batchCount := (len(words) + batchSize - 1) / batchSize

	for i := 0; i < batchCount; i++ {
		start, end := i*batchSize, (i+1)*batchSize
		if end > len(words) {
			end = len(words)
		}

		inserted, err := d.insertBatch(words[start:end])
		if err != nil {
			return totalInserted, fmt.Errorf("批次插入失败: %w", err)
		}
		totalInserted += inserted
	}

	return totalInserted, nil
}

// 插入单批次单词
func (d *WordDAO) insertBatch(batch []models.Word) (int, error) {
	query := "INSERT IGNORE INTO words (word, trans) VALUES "
	params := make([]interface{}, 0, len(batch)*2)

	for i, word := range batch {
		if i > 0 {
			query += ", "
		}
		query += "(?, ?)"
		params = append(params, word.Word, word.Trans)
	}

	result, err := d.db.Exec(query, params...)
	if err != nil {
		return 0, err
	}

	rowsAffected, err := result.RowsAffected()
	if err != nil {
		return 0, err
	}

	return int(rowsAffected), nil
}

// CleanWords 清空单词表数据
func (d *WordDAO) CleanWords() (int64, error) {
	result, err := d.db.Exec("TRUNCATE TABLE words")
	if err != nil {
		return 0, fmt.Errorf("清空失败: %w", err)
	}
	return result.RowsAffected()
}
